package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.ClientMapper;
import com.indusfo.spc.pojo.Client;
import com.indusfo.spc.service.ClientService;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ClientServiceImpl implements ClientService {

    private  static  final Logger logger = LoggerFactory.getLogger(ClientServiceImpl.class);

    @Resource
    private ClientMapper clientMapper;

    /**
     * 客户端设置更新
     *
     * @param client
     * @return  JSONObject
     */
    @Override
    public JSONObject updateClient(Client client) {
        String remark = client.getRemark();
        if(remark == null) {
            remark = "";
        }
        try {
            if(client.getClientId() == null) {
                throw new ParamsErrorException("请选择要编辑的工序");
            }
            Long[] shuzu = client.getShuzu();
            checkParam(client, remark,shuzu);

            // 调用存储过程
            int row = clientMapper.updateClient(client);
            if(row == 0) {
                throw new ModifyFailedException("数据编辑失败");
            }
            return JSONObject.oK("编辑成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /***
     * 不良对策查询（分页）
     *
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject selectAll(Client client) {
        List<Client> listClient = null;
        try {
            Integer pagesize = client.getPagesize();
            Integer pageindex = client.getPageindex();
            if(pagesize != null && pageindex != null) {
                client.setIncept(pagesize*(pageindex - 1));
            }
            Integer clientId = client.getClientId();
            String dim = client.getDim();
            if(clientId != null) {  //如果有id,则查询单个
                listClient = clientMapper.selectByClientId(client);
            }else{  //查询全部
                listClient = clientMapper.selectAll(client);
            }

            if (listClient.isEmpty()) {
                return JSONObject.oK("没有查询到数据", listClient, 0);
            }
            //查询分页总记录数
            int count = clientMapper.countClient(client); //返回查询到的总记录数
            return JSONObject.oK("查询成功", listClient, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /***
     * 部门新增
     *
     * @param client
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject insertBldc(Client client) {
        client.setDataState(1);
        String remark = client.getRemark();
        if(remark == null) {
            remark = "";
        }
        try {
            if(client.getClientId() != null) {
                throw new ParamsErrorException("新增不良对策时，不能填写id");
            }
            Long[] shuzu = client.getShuzu();
            checkParam(client, remark,shuzu);
            int	row = clientMapper.insertClient(client);
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 1 启用  2 删除  3停用 不良对策
     *
     * @param clientIds
     * @param dataState
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject deleteClient(Long[] clientIds, Integer dataState) {
        try {
            if(dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (clientIds == null) {
                throw new ParamsErrorException("客户端id不能为空");
            }
            // 执行存储过程
            int row = clientMapper.delteClient(clientIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 参数校验
     *
     * @param client
     * @param vcRemark
     */
    private void checkParam(Client client, String vcRemark, Long[] shuzu) {
        if (client.getClientTypeId() !=  1 && client.getClientTypeId() != 2 && client.getClientTypeId() != 3) {
            throw new ParamsErrorException("客户类型错误");
        }
        if (client.getRepairId() == null) {
            throw new ParamsErrorException("下线工序不能为空");
        }
        if (client.getScanType() !=  1 && client.getScanType() != 2 && client.getScanType() != 3) {
            throw new ParamsErrorException("扫描类型错误");
        }
        if (StringUtils.isEmpty(client.getClientCode())) {
            throw new ParamsErrorException("请填写客户端编号");
        }
        if (client.getClientCode().getBytes().length > 50) {
            throw new ParamsErrorException("客户端编号超过规定长度");
        }
        if (vcRemark.getBytes().length > 100) {
            throw new ParamsErrorException("说明字数超过规定长度");
        }
        // 客户端编号不能重复
        Integer depCounts = clientMapper.selectClient(client);
        if (depCounts !=0) {
            throw new ParamsErrorException("该客户端编号已存在");
        }
        client.setAutoPrint(0);
        client.setJumpPro(0);
        client.setRecodeErr(0);
        client.setBoundPallet(0);
        client.setBatchStart(0);
        client.setOfflineRemind(0);
        for(int i=0 ; i<shuzu.length ;i++){
            switch(shuzu[i].intValue()) {
                case 1:
                    client.setAutoPrint(1);
                    break;
                case 2:
                    client.setJumpPro(1);
                    break;
                case 3:
                    client.setRecodeErr(1);
                    break;
                case 4:
                    client.setBoundPallet(1);
                    break;
                case 5:
                    client.setBatchStart(1);
                    break;
                case 6:
                    client.setOfflineRemind(1);
                    break;
                default:
                    throw new ParamsErrorException("数组不正确");
            }
        }
    }
}
